package com.zhuchaooasystem.presenter.home.service;

import android.app.Activity;
import android.text.TextUtils;

import com.zhuchaooasystem.api.HttpFactory;
import com.zhuchaooasystem.api.RxResultHelper;
import com.zhuchaooasystem.base.BasePresenter;
import com.zhuchaooasystem.base.SchedulersCompat;
import com.zhuchaooasystem.entity.ServiceEntity;
import com.zhuchaooasystem.entity.UserInfo;

import java.util.HashMap;
import java.util.Map;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by zhangyajiang on 2016/12/22.
 */

public class ServiceSearchPresenter extends BasePresenter<ServiceSearchContract.View> implements ServiceSearchContract.Presenter {

    public ServiceSearchPresenter(Activity activity, ServiceSearchContract.View view) {
        super(activity, view);
    }


    @Override
    public void downSearchData(final int page, final boolean isShowDialog) {
        String search = mView.getSearch();

        if (TextUtils.isEmpty(search)) {
            handleError("请输入搜索内容");
            return;
        }

        if (isShowDialog){
            showLoading();
        }

        Map<String, String> map = new HashMap<>();
        map.put("memberId", UserInfo.getPersonalPk()+"");
        map.put("PageIndex", page + "");
        map.put("nonce_str",search);
        map.put("isOnWeek","-1");

        Subscription subscription = HttpFactory.getHttpApi().getService(map)
                .compose(SchedulersCompat.applyIoSchedulers())
                .compose(RxResultHelper.handleResult())
                .subscribe(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        if (isShowDialog){
                            LoadingDiaogDismiss();
                        }

                        ServiceEntity entity = (ServiceEntity) o;

                        if (entity != null) {
                            if (page == 1) {
                                mView.showData(entity);
                            } else if (page > 1) {
                                mView.showMoreData(entity);
                            }
                        }

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                        if (isShowDialog){
                            LoadingDiaogDismiss();
                        }

                        handleError(throwable);
                    }
                });
        addSubscrebe(subscription);
    }
}
